<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 刷新列表按钮 -->
    <el-button type="primary" class="refreshBtn" @click="refresh"
      >刷新</el-button
    >
    <!-- 卡片视图区 -->
    <el-card class="user-card">
      <!-- 搜索区 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.user_name"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 列表区 -->
      <el-table
        v-loading="loading"
        :data="userlist"
        stripe
        border
        height="75vh"
        class="table"
      >
        <el-table-column type="index" label="#"> </el-table-column>
        <el-table-column prop="user_name" label="用户名"> </el-table-column>
        <el-table-column prop="user_email" label="邮箱"> </el-table-column>
        <el-table-column prop="user_mobile" label="电话"> </el-table-column>
        <el-table-column prop="role" label="角色"> </el-table-column>
        <el-table-column prop="user_state" label="用户状态" width="150">
          <template slot-scope="props">
            <el-tooltip
              :content="props.row.user_state == '1' ? '启用' : '禁用'"
              placement="top"
              :enterable="false"
            >
              <el-switch
                v-model="props.row.user_state"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="changeStatus(props.row)"
              >
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template slot-scope="scope">
            <el-button
              @click="showEditDialog(scope.row.user_id)"
              type="primary"
              size="small"
            >
              <i class="el-icon-edit"></i>
              编辑</el-button
            >
            <el-button
              @click="removeUser(scope.row.user_id)"
              type="danger"
              size="small"
            >
              <i class="el-icon-delete"></i>
              删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.page"
        :page-sizes="[1, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        style="margin-top: 20px"
      >
      </el-pagination>
      <!-- 添加用户对话框 -->
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="addForm"
          :rules="addFormRules"
          ref="addFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="user_name">
            <el-input v-model="addForm.user_name"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="user_pwd">
            <el-input v-model="addForm.user_pwd"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="user_email">
            <el-input v-model="addForm.user_email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="user_mobile">
            <el-input v-model="addForm.user_mobile"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑用户对话框 -->
      <el-dialog
        title="编辑用户"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <!-- 内容主体区域 -->
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <el-form-item label="用户名" prop="user_name">
            <el-input disabled v-model="editForm.user_name"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="user_email">
            <el-input v-model="editForm.user_email"></el-input>
          </el-form-item>
          <el-form-item label="手机" prop="user_mobile">
            <el-input v-model="editForm.user_mobile"></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="editForm.role" placeholder="请选择角色">
              <el-option label="用户" value="用户"></el-option>
              <el-option label="管理员" value="管理员"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    // 自定义邮箱的校验规则
    var checkEmail = (rule, value, cb) => {
      // 正则表达式
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }
      cb(new Error("请输入合法的邮箱"));
    };
    // 自定义手机号的校验规则
    var checkMobile = (rule, value, cb) => {
      // 正则表达式
      const regMobile =
        /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
      if (regMobile.test(value)) {
        // 合法的手机号
        return cb();
      }
      cb(new Error("请输入合法的手机号"));
    };
    return {
      // 获取用户信息的参数对象
      queryInfo: {
        user_name: "",
        pagesize: 10, //条数
        page: 1, //页数
      },
      // 用户列表
      userlist: [],
      // 添加用户对话框显示隐藏
      addDialogVisible: false,
      // 总数
      total: 0,

      // 添加用户的验证规则
      addFormRules: {
        user_name: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,
            message: "长度在 3 到 10 个字符之间",
            trigger: "blur",
          },
        ],
        user_pwd: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符之间",
            trigger: "blur",
          },
        ],
        user_email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail },
        ],
        user_mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile },
        ],
      },
      // 添加用户的表单信息
      addForm: {
        user_name: "",
        user_pwd: "",
        user_mobile: "",
        user_email: "",
      },
      // 编辑用户的个人信息
      editForm: {},
      // 编辑用户的表单验证
      editFormRules: {
        user_email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail },
        ],
        user_mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkMobile },
        ],
      },
      // 编辑用户的表单信息
      editForm: {},
      // 编辑用户对话框的显示隐藏
      editDialogVisible: false,
      // 加载的显示隐藏
      loading: false,
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    // 获取用户列表
    async getUserList() {
      this.loading = true;
      const { data: res } = await this.$http.get("/api/users", {
        params: this.queryInfo,
        ...this.getToken,
      });
      if (res.code !== 1)
        return this.$message.console.error("获取用户列表失败！");
      this.loading = false;
      this.userlist = res.data.list;
      this.total = res.data.total;
    },
    // 刷新列表按钮
    refresh() {
      (this.queryInfo.user_name = ""),
        (this.queryInfo.pagesize = 10),
        (this.queryInfo.page = 1);
      this.getUserList();
    },
    // 改变用户状态
    async changeStatus(obj) {
      const { data: res } = await this.$http.put(
        "/api/users/" + obj.user_id,
        { user_state: obj.user_state },
        this.getToken
      );
      if (res.code !== 1) return this.$message.error("修改用户状态失败！");
      this.$message.success("修改用户状态成功！");
      // console.log(res);
    },
    // 添加用户对话框关闭按钮
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },
    // 添加用户确定按钮
    addUser() {
      console.log(this.addForm);
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "/api/users/0",
          this.addForm,
          this.getToken
        );
        if (res.code !== 1) return this.$message.error("添加用户失败！");
        this.$message.success("添加用户成功！");
        this.addDialogVisible = false;
        this.getUserList();
      });
    },
    // 编辑按钮
    async showEditDialog(id) {
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get(
        "/api/users/" + id,
        this.getToken
      );
      if (res.code !== 1) return this.$message.error("获取此用户信息失败！");
      let { user_id, user_name, user_email, user_mobile, role } = res.data[0];
      this.editForm = { user_id, user_name, user_email, user_mobile, role };
      // console.log(this.editForm);
    },
    // 搜索按钮
    search() {
      this.queryInfo.page = 1;
      this.getUserList();
    },
    // 删除按钮
    async removeUser(id) {
      const isremove = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (isremove === "cancel") return this.$message.info("已取消删除！");
      const { data: res } = await this.$http.delete("/api/users/" + id, {
        ...this.getToken,
      });
      if (res.code !== 1) return this.$message.error("删除用户失败！");
      this.$message.success("删除用户成功！");
      this.total--;
      if (!(this.total % this.queryInfo.pagesize)) this.queryInfo.page--;
      this.getUserList();
    },
    // 编辑用户对话框的关闭按钮
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },
    // 编辑用户对话框的确认按钮
    async editUser() {
      const id = this.editForm.user_id;
      const { data: res } = await this.$http.put(
        "/api/users/" + id,
        this.editForm,
        this.getToken
      );
      if (res.code !== 1) return this.$message.error("修改失败！");
      this.$message.success("修改成功！");
      this.editDialogVisible = false;
      this.getUserList();
    },
    // 监听条数改变
    handleSizeChange(newsize) {
      this.queryInfo.pagesize = newsize;
      this.getUserList();
    },
    // 监听页数改变
    handleCurrentChange(newpage) {
      this.queryInfo.page = newpage;
      this.getUserList();
    },
  },
  computed: {
    getToken() {
      return { headers: { authorization: sessionStorage.getItem("token") } };
    },
  },
};
</script>

<style lang="less" scoped>
</style>